package com.naihe.anderson.sms.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.adapter.FriendCheckAdapter;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.entity.ContactUser;
import com.naihe.anderson.sms.manager.ContactMgr;
import com.naihe.anderson.sms.widgets.MyView;

public class FriendCheckActivity extends Activity implements OnItemClickListener, OnScrollListener{

	private final static int SHOW_LOCKER = 0;
	public final static int SHOW_VIEW_PY = 1;
	public final static int SHOW_VIEW_UP = 2;
	private final static int THREAD_HIDE_TIME = 1500;
	private final static int TIMER_HIDE_TIME = 2000;
	
	FriendCheckAdapter friendCheckAdapter;
	ListView friendList;
	
	List<ContactUser> contactUsers;
	NhSmsApp nhSmsApp;
	ContactMgr contactMgr;
	
	Button btn_edit_friend;
	Button btn_back;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.friend_check_layout);
        
        contactUsers = new ArrayList<ContactUser>();
        nhSmsApp = (NhSmsApp) getApplication();
        contactMgr = nhSmsApp.getContactMgr();
        initView();
        initTxtOverlay();
        initData();
    }
	
	private void initTxtOverlay(){
		txtOverlay = (TextView) LayoutInflater.from(this).inflate(R.layout.list_popup_char_hint, null);
		txtOverlay.setVisibility(View.INVISIBLE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);
		windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		windowManager.addView(txtOverlay, lp);
		
		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case SHOW_LOCKER:
					if(txtOverlay.isShown()){
						txtOverlay.setVisibility(View.INVISIBLE);
					}
					break;
				case SHOW_VIEW_PY:
					friendList.setOnScrollListener(null);
    				int localObject = msg.getData().getInt("localObject", -1);
    				if(localObject >= 0 && localObject < 26){
    					txtOverlay.setText(py[localObject]);
    					if(sectionMap.get(py[localObject]) != null)
    						friendList.setSelection(sectionMap.get(py[localObject]).intValue());
    					txtOverlay.setVisibility(View.VISIBLE);
    				}else{
    					txtOverlay.setVisibility(View.INVISIBLE);
    				}
    				break;
				case SHOW_VIEW_UP:
					txtOverlay.setVisibility(View.INVISIBLE);
					friendList.setOnScrollListener(FriendCheckActivity.this);
					break;
				default:
					super.handleMessage(msg);
				}
			}
		};
		disapearThread = new DisapearThread();
		
		myView = (MyView) findViewById(R.id.myview);
        myView.setHandler(handler);
	}
	
	public void initView(){
		friendList = (ListView) findViewById(R.id.friend_list);
		btn_edit_friend = (Button) findViewById(R.id.btn_edit_friend);
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
				System.gc();
			}
		});
		btn_edit_friend.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				backCheckData();
				finish();
				System.gc();
			}
		});
		
	}
	
	private void backCheckData(){
		String backString = "";
		for(Map.Entry<ContactUser, Boolean> entityMap : friendCheckAdapter.getCheckIfMap().entrySet())   
		{
			ContactUser contactUser = entityMap.getKey();
			if(entityMap.getValue()){
				backString += contactUser.getName() + "<" + contactUser.getNumbers() + ">,";
			}
		}
		
		Intent aintent = new Intent(FriendCheckActivity.this, MakeNewMessageActivity.class);
		aintent.putExtra("backString", backString);
		setResult(RESULT_OK, aintent);
	}
	
	public void initData(){
		contactUsers.addAll(contactMgr.getContactData1T1());
		sections = new String[contactUsers.size()];
		for (int i = 0; i < contactUsers.size(); i++) {
			ContactUser user = contactUsers.get(i);
			
			String ch = user.getName().substring(0,1);
	    	String headPy = user.getChineseNameCode().substring(0,1).toUpperCase();
	    	if(sectionMap.get(headPy) == null){
	    		sectionMap.put(headPy, i);
	    	}
	    	sections[i] = ch;
		}
		friendCheckAdapter = new FriendCheckAdapter(FriendCheckActivity.this, contactUsers);
		friendList.setAdapter(friendCheckAdapter);
		friendList.setOnItemClickListener(this);
		friendList.setOnScrollListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		ContactUser entityObj = (ContactUser) friendCheckAdapter.getItem(position);
		if(entityObj == null) return ;
		CheckBox cb = (CheckBox)view.findViewById(R.id.widget_checkbox);
		boolean ischecked = cb.isChecked();
		cb.setChecked(!ischecked);
		
		friendCheckAdapter.setCheckIfMap(entityObj, !ischecked);
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu_check, menu);
    	return super.onPrepareOptionsMenu(menu);
	}
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menu_check_all) {
			friendCheckAdapter.setCheckAll(true);
			friendCheckAdapter.notifyDataSetChanged();
			return true;
		} else if (item.getItemId() == R.id.menu_invite) {
			backCheckData();
			finish();
			System.gc();
			return true;
		} else if (item.getItemId() == R.id.menu_check_cancel) {
			friendCheckAdapter.setCheckAll(false);
			friendCheckAdapter.notifyDataSetChanged();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

    public void onDestroy() {
		super.onDestroy();
		txtOverlay.setVisibility(View.INVISIBLE);
		windowManager.removeView(txtOverlay);
		if(lockTimer != null) {
			lockTimer.cancel();
			lockTimer.purge();
			lockTimer = null;
		}
	}
    
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if(sections != null && sections.length > 0){
			if(view.getLastVisiblePosition() == view.getCount()-1){
				txtOverlay.setText(sections[totalItemCount - 1]);
			}else{
				txtOverlay.setText(sections[firstVisibleItem + (visibleItemCount>>1)]);
			}
		}
	}
	
	String[] sections;
	Map<String, Integer> sectionMap = new HashMap<String, Integer>();
	private String py [] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
			"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
			"X", "Y", "Z" };
	
	private WindowManager windowManager;
	private TextView txtOverlay;
	private MyView myView;
	private Handler handler;
	private DisapearThread disapearThread;
	private int scrollState;
	private Timer lockTimer;
	
	private class LockTimerTask extends TimerTask{
		@Override
		public void run() {
			handler.sendMessage(handler.obtainMessage(SHOW_LOCKER));
		}
	};
	
	private class DisapearThread implements Runnable {
		public void run() {
			if (scrollState == ListView.OnScrollListener.SCROLL_STATE_IDLE) {
				txtOverlay.setVisibility(View.INVISIBLE);
			}
		}
	}
	
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub
		this.scrollState = scrollState;
		if (scrollState == ListView.OnScrollListener.SCROLL_STATE_IDLE) {
			handler.removeCallbacks(disapearThread);
			handler.postDelayed(disapearThread, THREAD_HIDE_TIME);
		} else if (scrollState == ListView.OnScrollListener.SCROLL_STATE_FLING) {
			txtOverlay.setVisibility(View.VISIBLE);
			if(lockTimer != null) {
				lockTimer.cancel();
				lockTimer.purge();
				lockTimer = null;
			}
		} else {
			txtOverlay.setVisibility(View.VISIBLE);
			if(lockTimer != null) {
				lockTimer.cancel();
				lockTimer.purge();
				lockTimer = null;
			}
			lockTimer = new Timer();
			lockTimer.schedule(new LockTimerTask(), TIMER_HIDE_TIME);
		}
	}
}
